package com.cp.support.gray;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.cloud.netflix.ribbon.RibbonClientSpecification;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

/**
 * @author YangXiaoLong
 * 2022/11/1 19:01
 */
@SuppressWarnings("all")
public class GrayRibbonClientConfigurationRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private static final String gray_enabled_key = "ribbion.gray.enabled";
    Environment environment;

    public static String DEFALT_RULE_CLASS = DefaultGrayRibbonRule.class.getName();

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata,
                                        BeanDefinitionRegistry registry) {
        String enabledStr = environment.getProperty("ribbion.gray.enabled");
        if (enabledStr == null) {
            return;
        }
        boolean enabled;
        try {
            enabled = Boolean.parseBoolean(enabledStr);
        } catch (Exception e) {
            return;
        }
        if (!enabled) {
            return;
        }
        String serviceNames = environment.getProperty("ribbion.gray.serviceNames");
        if (StringUtils.isEmpty(serviceNames)) {
            return;
        }
        String[] serviceArr = serviceNames.split(",");
        String ribbionRuleClass;
        ribbionRuleClass = environment.getProperty("ribbion.gray.rule");
        if (StringUtils.isEmpty(ribbionRuleClass)) {
            ribbionRuleClass = DEFALT_RULE_CLASS;
        }
        for (String serviceName : serviceArr) {
            registerClientConfiguration(registry, serviceName, ribbionRuleClass);
        }
    }

    private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
                                             Object configuration) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .genericBeanDefinition(RibbonClientSpecification.class);
        builder.addConstructorArgValue(name);
        builder.addConstructorArgValue(configuration);
        registry.registerBeanDefinition(name + ".RibbonClientSpecification",
                builder.getBeanDefinition());
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
